<template>
  <div>
    <van-nav-bar class="my-nav-bar" title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请填写手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请填写正确手机号'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请填写验证码"
        required
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请填写正确验证码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isDisabled"
          loading-text="登录..."
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/login.js'
import { saveToken } from '@/utils/token'
export default {
  name: 'login',
  data () {
    return {
      mobile: '15989757322',
      code: '246810',
      isLoading: false,
      isDisabled: false
    }
  },
  methods: {
    onSubmit (values) {
      this.isLoading = true
      this.isDisabled = true
      userLogin(values)
        .then(res => {
          saveToken(res.data.data)
          setTimeout(() => {
            this.isLoading = false
            this.isDisabled = false
            this.$toast.success('登录成功')
            const back = this.$route.query.back
            // console.log(back)
            if (this.$route.query.back) {
              this.$router.push({ path: back })
            } else {
              this.$router.push({ path: '/home' })
            }
          }, 500)
        })
        .catch(err => {
          this.isLoading = false
          this.isDisabled = false
          this.$toast.fail('登录失败')
          console.log('err', err)
        })
    }
  }
}
</script>

<style lang="less">
.my-nav-bar.van-nav-bar {
  background-color: #3789f4;
  .van-nav-bar__title {
    color: #fff;
  }
}
</style>
